<template>
  <!--历史记录列表-->
  <el-dialog v-model="historyDialog.visible" :title="historyDialog.title" @close="closeHistoryDialog">
    <el-table :data="historyData" stripe border v-loading="tableLoading">
      <el-table-column prop="id" label="主编号" min-width="150" align="center" />
      <el-table-column prop="operatorName" label="操作员" min-width="150" align="center" />
      <el-table-column prop="createTime" label="记录时间" min-width="150" align="center" />
      <el-table-column label="操作" width="150px">
        <template #default="scope">
          <el-link type="primary" icon="Tickets" v-if="!isEdit">
            <span style="padding: 0 5px" @click="handleOpenDialog(scope.row, 'info')">查看</span>
          </el-link>
          <el-link type="primary" icon="Tickets" v-if="isEdit">
            <span style="padding: 0 5px" @click="handleOpenDialog(scope.row, 'edit')">编辑</span>
          </el-link>
          <el-link type="danger" icon="Tickets" v-if="isEdit">
            <span style="padding: 0 5px" @click="handleDelete(scope.row.id)">删除</span>
          </el-link>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  <!-- 处理记录表单弹窗 -->
  <el-dialog v-model="formDialog.visible" :title="formDialog.title" width="650px" @close="handleCloseDialog">
    <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="120px" inline v-loading="formLoading">
      <el-form-item label="操作员" prop="operationId">
        <el-select v-model="formData.operationId" style="width:150px" :disabled="!isEdit">
          <el-option v-for="item in workerOptions" :value="item.userId" :label="item.username"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="输入物" prop="input">
        <el-input v-model="formData.inputObj" placeholder="输入物" style="width:200px;margin-right: 5px;"
          :disabled="!isEdit" />
        <el-input-number v-model="formData.inputWeight" :precision="2" :step="0.1" placeholder="" style="width: 200px"
          controls-position="right" :disabled="!isEdit">
          <template #suffix>千克(kg)</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="输出物" prop="output">
        <el-input v-model="formData.outputObj" placeholder="输出物" style="width:200px;margin-right: 5px;"
          :disabled="!isEdit" />
        <el-input-number v-model="formData.outputWeight" :precision="2" :step="0.1" placeholder="" style="width: 200px"
          controls-position="right" :disabled="!isEdit">
          <template #suffix>千克(kg)</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="开始处理时间" prop="startTime">
        <el-date-picker v-model="formData.startTime" type="datetime" placeholder="开始处理时间"
          value-format="YYYY-MM-DD HH:mm:ss" :disabled="!isEdit" />
      </el-form-item>

      <el-form-item label="结束处理时间" prop="endTime">
        <el-date-picker v-model="formData.endTime" type="datetime" placeholder="结束处理时间"
          value-format="YYYY-MM-DD HH:mm:ss" :disabled="!isEdit" />
      </el-form-item>

      <el-form-item label="处理过程文件" prop="fileList">
        <FileUpload v-model="formData.fileList" :isEdit="isEdit"></FileUpload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="display: flex;justify-content: center;" v-if="isEdit">
        <el-button @click="handleCloseDialog()">取消</el-button>
        <el-button type="primary" @click="handleSubmit()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, defineProps, defineExpose, computed } from 'vue';
import ProcessRecordAPI from '@/api/system/process-record';
import OrgAPI from '@/api/system/org';
import { useUserStore } from "@/store";
import FileUpload from "@/components/Upload/FileUpload.vue";

const tableLoading = ref(false)
const formLoading = ref(false)

const dataFormRef = ref(null)
const historyDialog = reactive({
  visible: false,
  title: '历史记录',
});
const formDialog = reactive({
  visible: false,
  title: '处理记录',
  type: ''
})
const isEdit = computed(() => {
  return formDialog.type == 'edit'
})

const historyData = ref()
// 处理记录表单数据
const formData = reactive({
  operationId: '',
  requestId: "",
  processStatus: 0,
  startTime: "",
  endTime: "",
  inputObj: "",
  inputWeight: "",
  outputObj: "",
  outputWeight: "",
  fileList: [],
  createTime: "",
});

// 处理记录表单校验规则
const rules = reactive({
  operationId: [{ required: true, message: '请选择操作员', trigger: 'change' }],
  input: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (formData.inputObj == '') {
          callback(new Error('请输入输入物名称'));
        } else if (formData.inputWeight == '') {
          callback(new Error('请输入输入物重量'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
  output: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (formData.outputObj == '') {
          callback(new Error('请输入输出物名称'));
        } else if (formData.outputWeight == '') {
          callback(new Error('请输入输出物重量'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    {
      validator: (_, value, callback) => {
        if (formData.endTime && new Date(value) > new Date(formData.endTime)) {
          callback(new Error('开始时间不能晚于结束时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (_, value, callback) => {
        if (formData.startTime && new Date(value) < new Date(formData.startTime)) {
          callback(new Error('结束时间不能早于开始时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  fileList: [
    {
      required: true,
      validator: (_, value) => isEdit.value ? value.length > 0 : true,
      message: '请上传处理过程文件',
      trigger: 'change'
    }
  ],
});

const openHistoryDialog = (requestId, type) => {
  historyDialog.visible = true;
  formDialog.type = type
  getHistoryRecord(requestId)
};

const tempRequestId = ref("")
const getHistoryRecord = async (requestId) => {
  tempRequestId.value = requestId;
  if (tempRequestId.value) {
    tableLoading.value = true;
    const data = await ProcessRecordAPI.getHistoryRecord(tempRequestId.value);
    historyData.value = data;
    tableLoading.value = false;
  }
};
const closeHistoryDialog = () => {
  tempRequestId.value = ""
  historyDialog.visible = false;
};

const workerOptions = ref()
async function handleOpenDialog(row, type) {
  formDialog.visible = true;  // 立即显示弹窗
  formDialog.type = type;
  // 添加 await 确保数据加载完成
  workerOptions.value = await OrgAPI.getWorkersByRequestId(row.requestId);

  if (row.id && row.processStatus != 0) {
    // 添加 await 确保表单数据加载
    formLoading.value = true;
    const data = await ProcessRecordAPI.getFormData(row.id);
    Object.assign(formData, data);
    formLoading.value = false;
    if (formDialog.type == 'edit') {
      formDialog.title = "修改处理记录";
    } else if (formDialog.type == 'info') {
      formDialog.title = "查看处理记录";
    }
  } else {
    formData.requestId = row.requestId;
    formDialog.title = "新增处理记录";
  }
}
/** 提交处理记录表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      const id = formData.id;
      if (id) {
        ProcessRecordAPI.updateRecord(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ProcessRecordAPI.addRecord(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭处理记录弹窗 */
function handleCloseDialog() {
  formDialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

const removeIds = ref([])
/** 删除历史记录 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ProcessRecordAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}
//暴露方法
defineExpose({
  openHistoryDialog,
  closeHistoryDialog,
  handleOpenDialog,
});
</script>

<style lang="scss" scoped></style>
